/*
 *@(#)CodebushMailRetriever.java 1.0 Feb 28, 2008
 *Copyright Fution Bai
 *
 */
package codebush.service.support.mail;

import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

import codebush.service.Help;

/**
 * 
 * @author Fution Bai
 * @since 1.0
 */
public class CodebushMailRetriever {

	private String host;
	private String username;
	private String password;
	private Help help;
	
	/**
	 * retrieve the inbox messages, post them, then delete them
	 * @return
	 */
	public Message[] retrieve() {
		try {
			Session session = Session.getDefaultInstance(this.initialProperties(), new AuthenticatorBai());
			Store store;
			store = session.getStore("pop3");
			store.connect();

			Folder folder = store.getFolder("INBOX");
			folder.open(Folder.READ_WRITE);
			Message[] messages = folder.getMessages();
			for(int i = 0; i< messages.length; i++){
				messages[i].setFlag(Flags.Flag.DELETED, true);
			}
			this.getHelp().postRetrievedMessage(messages);
			folder.close(true);
			store.close();
			return messages;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * initial the session propertites
	 * 
	 * @return
	 */
	private Properties initialProperties() {
		Properties props = System.getProperties();
		/**
		 * below is for ssl connection Security.addProvider(new
		 * 
		 * <code>com.sun.net.ssl.internal.ssl.Provider()); final String SSL_FACTORY =
		 * "javax.net.ssl.SSLSocketFactory";
		 * props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
		 * props.setProperty("mail.pop3.socketFactory.fallback", "false");
		 * props.setProperty("mail.pop3.port", "995");
		 * props.setProperty("mail.pop3.socketFactory.port", "995");</code>
		 */
		props.put("mail.pop3.host", host);
		return props;
	}
	
	/**
	 * annoying setters and getters
	 */
	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Help getHelp() {
		return help;
	}

	public void setHelp(Help help) {
		this.help = help;
	}


}
